<template>
  <ActionPanel :loading="loading">
    <div class="font-size-16px font-600 mb2">【{{seed.label}}】基本信息</div>
    <el-form ref="formRef" :model="data" :rules="cross.rules" status-icon>
      <el-form-item v-for="(column, i) in cross.columns" :label="column.label" :prop="toCamelCase(column.name)" :key="i">
        <component :is="getElement(column.type, 'write', action.elements?.[column.name]?.element)"
          v-model="data[toCamelCase(column.name)]" :action="action" :column="column"
          v-bind="action.elements?.[column.name]?.elementProps" @keyup.enter="save"
        />
      </el-form-item>
    </el-form>
    
    <template v-for="(relation, cross) in cross.crosses">
      <SaveList v-if="relation.type == 'hasMany'" :has-many="relation" :data="data[cross]" />
      <Save v-else :has-one="relation" :data="data[cross]" :column="2" />
    </template>
    <template #footer>
      <div class="flex justify-center items-center">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button v-if="close" @click="close">关闭</el-button>
      </div>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ElButton, ElForm, ElFormItem } from 'element-plus'
  import { Save, SaveList } from '@/components/crud'
  import { inject, ref } from 'vue'
  import { toCamelCase } from '@/utils/func'
  import { buildDeclared, getCross, getDeclares, getInitData } from '@/seed-application/utils/SeedUtil'
  import { saveApi } from '@/seed-application/api'  
  import { getAction, unitKey } from '@/seed-application'
  import { ActionPanel } from '@/components/ActionPanel'
  import { closePopupKey } from '@/components/Popup'
  import { Unit } from '@/seed-application/types'
  import { getElement } from '@/seed-application'
  import feedback from '@/utils/feedback'

  export type PropsType = {actionName: string, seedName?: string, microName?: string}
  const props = defineProps<PropsType>()
  const action = getAction(props.actionName, props.seedName, props.microName)
  const seed = action.seed
  console.log('DefaultSave===', action, seed)

  const close = inject<() => void>(closePopupKey, void 0)
  const unit = inject<Unit>(unitKey, void 0)

  const formRef = ref()
  const declares = getDeclares(action);

  const declared = buildDeclared(seed, declares)
  const data = ref(getInitData(seed, declared))
  const cross = getCross(seed, declared, action.elements)

  const loading = ref(false)
  async function save() {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        await saveApi(action, data.value)
        feedback.msgSuccess(`保存${seed.label}成功`)
        data.value = getInitData(seed, declared)
        loading.value = false
        unit?.refresh?.()
        close?.()
      } else {
        // console.log('error submit!', fields)
        // feedback.alertError(fields)
      }
    })
  }
</script>